package cn.basic.social.demo.service.impl;

import cn.basic.social.api.qwtalk.channel.thirdparty.request.ThirdpartDataCallbackRequest;
import cn.basic.social.api.qwtalk.channel.thirdparty.request.ThirdpartInstructCallbackRequest;
import cn.basic.social.api.qwtalk.channel.thirdparty.request.ThirdpartVerificationRequest;
import cn.basic.social.api.qwtalk.channel.thirdparty.response.ThirdpartDataCallbackResponse;
import cn.basic.social.api.qwtalk.channel.thirdparty.response.ThirdpartInstructCallbackResponse;
import cn.basic.social.api.qwtalk.channel.thirdparty.response.ThirdpartVerificationResponse;
import cn.basic.social.demo.exception.BusinessException;
import cn.basic.social.demo.service.SocialCallbackService;
import cn.basic.social.manager.config.SocialConfigProperties;
import cn.basic.social.manager.config.SocialRequestFactory;
import cn.basic.social.manager.handler.qwtalkhandler.ThirdpartQwService;
import cn.basic.social.manager.handler.qwtalkhandler.thirdparty.DataCallbackServiceImpl;
import cn.basic.social.manager.handler.qwtalkhandler.thirdparty.DataVerificationServiceImpl;
import cn.basic.social.manager.handler.qwtalkhandler.thirdparty.InstructCallbackServiceImpl;
import cn.basic.social.manager.handler.qwtalkhandler.thirdparty.InstructVerificationServiceImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName SocialCallbackServiceImpl
 * @Description 第三方服务回调接口实现类
 * @Author zlf
 * @Date 2023/9/8 10:54
 */
@Slf4j
@Component
public class SocialCallbackServiceImpl implements SocialCallbackService {

    @Autowired
    private SocialRequestFactory socialRequestFactory;

    @Override
    public Object verificationUrl(HttpServletRequest request) {
        try {
            ThirdpartVerificationResponse callbackResponse = socialRequestFactory.doExecute(SocialConfigProperties.TypeEnum.QiWei_ThirdPart,
                    "login", (providerConfig, redisCache) -> {
                        String msgSignature = request.getParameter("msg_signature");
                        String timeStamp = request.getParameter("timestamp");
                        String nonce = request.getParameter("nonce");
                        String echostr = request.getParameter("echostr");
                        log.info("企业微信加密签名: {},时间戳: {},随机数: {},加密的字符串: {}", msgSignature, timeStamp, nonce, echostr);

                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("msgSignature", msgSignature);
                        jsonObject.put("timestamp", timeStamp);
                        jsonObject.put("nonce", nonce);
                        jsonObject.put("echostr", echostr);

                        ThirdpartVerificationRequest callbackRequest = new ThirdpartVerificationRequest();
                        callbackRequest.setJsonParamBody(jsonObject.toJSONString());

                        ThirdpartQwService thirdpartQwService = new InstructVerificationServiceImpl();
                        ThirdpartVerificationResponse response = (ThirdpartVerificationResponse) thirdpartQwService.invoke(callbackRequest, providerConfig, redisCache);
                        if (!response.isSuccess()) {
                            throw new BusinessException("回调验证URL失败:" + response.getErrmsg());
                        }
                        log.info("验证回调返回值：{}", !ObjectUtils.isEmpty(response) ? JSONObject.toJSONString(response) : null);
                        return response;
                    });
            log.info("企业微信验证URL解密结果：{}", !ObjectUtils.isEmpty(callbackResponse) ? callbackResponse.getDecodeEchoStr() : null);
            return callbackResponse.getDecodeEchoStr();
        } catch (Exception e) {
            log.error("验证URL失败，case：" + e, e);
            throw new BusinessException("验证URL失败！" + e.getMessage());
        }
    }

    @Override
    public void getCallBackParameter(HttpServletRequest request, String body, String applicationName) {
        try {
            ThirdpartInstructCallbackResponse callbackResponse = socialRequestFactory.doExecute(SocialConfigProperties.TypeEnum.QiWei_ThirdPart,
                    applicationName, (providerConfig, redisCache) -> {
                        String msgSignature = request.getParameter("msg_signature");
                        String timeStamp = request.getParameter("timestamp");
                        String nonce = request.getParameter("nonce");
                        log.info("企业微信加密签名: {},时间戳: {},随机数: {}", msgSignature, timeStamp, nonce);

                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("msgSignature", msgSignature);
                        jsonObject.put("timestamp", timeStamp);
                        jsonObject.put("nonce", nonce);
                        jsonObject.put("body", body);

                        ThirdpartInstructCallbackRequest callbackRequest = new ThirdpartInstructCallbackRequest();
                        callbackRequest.setJsonParamBody(jsonObject.toJSONString());

                        ThirdpartQwService thirdpartQwService = new InstructCallbackServiceImpl();
                        ThirdpartInstructCallbackResponse response = (ThirdpartInstructCallbackResponse) thirdpartQwService.invoke(callbackRequest, providerConfig, redisCache);
                        if (!response.isSuccess()) {
                            throw new BusinessException("回调验证URL失败:" + response.getErrmsg());
                        }
                        log.info("验证回调返回值：{}", !ObjectUtils.isEmpty(response) ? JSONObject.toJSONString(response) : null);
                        return response;
                    });
            log.info("企业微信指令回调结果：{}", !ObjectUtils.isEmpty(callbackResponse) ? JSON.toJSONString(callbackResponse) : null);
        } catch (Exception e) {
            log.error("验证失败，case：" + e, e);
            throw new BusinessException("验证失败！" + e.getMessage());
        }
    }

    @Override
    public Long verificationUrl(String sVerifyMsgSig, Integer sVerifyTimeStamp, String sVerifyNonce, String sVerifyEchoStr) {
        try {
            ThirdpartVerificationResponse callbackResponse = socialRequestFactory.doExecute(SocialConfigProperties.TypeEnum.QiWei_ThirdPart,
                    "login", (providerConfig, redisCache) -> {
                        log.info("企业微信加密签名: {},时间戳: {},随机数: {},加密的字符串: {}", sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr);

                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("msgSignature", sVerifyMsgSig);
                        jsonObject.put("timestamp", sVerifyTimeStamp);
                        jsonObject.put("nonce", sVerifyNonce);
                        jsonObject.put("echostr", sVerifyEchoStr);

                        ThirdpartVerificationRequest callbackRequest = new ThirdpartVerificationRequest();
                        callbackRequest.setJsonParamBody(jsonObject.toJSONString());

                        ThirdpartQwService thirdpartQwService = new DataVerificationServiceImpl();
                        ThirdpartVerificationResponse response = (ThirdpartVerificationResponse) thirdpartQwService.invoke(callbackRequest, providerConfig, redisCache);
                        if (!response.isSuccess()) {
                            throw new BusinessException("回调验证URL失败:" + response.getErrmsg());
                        }
                        log.info("验证回调返回值：{}", !ObjectUtils.isEmpty(response) ? JSONObject.toJSONString(response) : null);
                        return response;
                    });
            log.info("企业微信验证URL解密结果：{}", !ObjectUtils.isEmpty(callbackResponse) ? callbackResponse.getDecodeEchoStr() : null);
            return Long.valueOf(callbackResponse.getDecodeEchoStr());
        } catch (Exception e) {
            log.error("验证URL失败，case：" + e, e);
            throw new BusinessException("验证URL失败！" + e.getMessage());
        }
    }

    @Override
    public void getCallBackParameter(String sVerifyMsgSig, Integer sVerifyTimeStamp, String sVerifyNonce, String body, String applicationName) {
        try {
            ThirdpartInstructCallbackResponse callbackResponse = socialRequestFactory.doExecute(SocialConfigProperties.TypeEnum.QiWei_ThirdPart,
                    applicationName, (providerConfig, redisCache) -> {
                        log.info("企业微信加密签名: {},时间戳: {},随机数: {}", sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce);

                        JSONObject jsonObject = new JSONObject();
                        jsonObject.put("msgSignature", sVerifyMsgSig);
                        jsonObject.put("timestamp", sVerifyTimeStamp);
                        jsonObject.put("nonce", sVerifyNonce);
                        jsonObject.put("body", body);

                        ThirdpartDataCallbackRequest callbackRequest = new ThirdpartDataCallbackRequest();
                        callbackRequest.setJsonParamBody(jsonObject.toJSONString());

                        ThirdpartQwService thirdpartQwService = new DataCallbackServiceImpl();
                        ThirdpartDataCallbackResponse response = (ThirdpartDataCallbackResponse) thirdpartQwService.invoke(callbackRequest, providerConfig, redisCache);
                        if (!response.isSuccess()) {
                            throw new BusinessException("回调验证URL失败:" + response.getErrmsg());
                        }
                        log.info("验证回调返回值：{}", !ObjectUtils.isEmpty(response) ? JSONObject.toJSONString(response) : null);
                        return response;
                    });
            log.info("企业微信数据回调结果：{}", !ObjectUtils.isEmpty(callbackResponse) ? JSON.toJSONString(callbackResponse) : null);
        } catch (Exception e) {
            log.error("验证失败，case：" + e, e);
            throw new BusinessException("验证失败！" + e.getMessage());
        }
    }
}
